package com.docker.core.third.websocket;

import com.docker.core.mvc.Remark;

import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author ldl
 * @Create 2020/08/14 014 17:15
 */
@Remark("websocket连接池")
public class WebsocketPool {

    //用来存放每个客户端对应的WebSocket连接对象。
    private static Map<String, WebsocketPool> poolMap = new ConcurrentHashMap<>();

    //通讯连接键
    private String connect_key;
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //最后通信时间
    private String conn_lastime;

    /**
     * @Param: [connectKey 连接键, session 连接session, connLastime 最后通讯时间]
     * @return: void
     * @Author: ldl
     * @Create: 2020/08/18 018 14:09
     */
    @Remark("添加连接池")
    public static void addSocketPool(String connectKey, Session session, String connLastime) {
        addSocketPool(connectKey, new WebsocketPool(connectKey, session, connLastime));
    }

    /**
     * @Param: [connectKey 连接键, socketPool 连接池]
     * @return: void
     * @Author: ldl
     * @Create: 2020/08/18 018 14:10
     */
    @Remark("添加连接池")
    public static void addSocketPool(String connectKey, WebsocketPool socketPool) {
        poolMap.put(connectKey, socketPool);
    }

    /**
     * @Param: [connectKey 连接键]
     * @return: 连接池对象
     * @Author: ldl
     * @Create: 2020/08/18 018 14:10
     */
    @Remark("根据应用标识获取连接池")
    public static WebsocketPool getSocketPool(String connectKey) {
        return poolMap.get(connectKey);
    }

    /**
     * @Param: [session 连接session]
     * @return: 连接池对象
     * @Author: ldl
     * @Create: 2020/08/18 018 14:11
     */
    @Remark("根据session获取连接池")
    public static WebsocketPool getSocketPool(Session session) {
        for (WebsocketPool socketPool : poolMap.values()) {
            if (session.equals(socketPool.getSession())) {
                return socketPool;
            }
        }
        return null;
    }

    /**
     * @Param: []
     * @return: 连接池map集合
     * @Author: ldl
     * @Create: 2020/08/18 018 14:11
     */
    @Remark("获取全部连接池")
    public static Map<String, WebsocketPool> getPoolMap() {
        return poolMap;
    }

    public WebsocketPool(String connectKey, Session session, String conn_lastime) {
        this.connect_key = connectKey;
        this.session = session;
        this.conn_lastime = conn_lastime;
    }

    public String getConnect_key() {
        return connect_key;
    }

    public void setConnect_key(String connect_key) {
        this.connect_key = connect_key;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getConn_lastime() {
        return conn_lastime;
    }

    public void setConn_lastime(String conn_lastime) {
        this.conn_lastime = conn_lastime;
    }
}
